package com.work.work.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.work.work.common.R;
import com.work.work.dto.BatchUpdateTeamRequest;
import com.work.work.dto.LoginRequest;
import com.work.work.dto.LoginResponse;
import com.work.work.dto.UserDTO;
import com.work.work.entity.User;
import com.work.work.service.UserService;
import com.work.work.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public R<LoginResponse> login(@RequestBody LoginRequest request) {
        // 验证用户名密码
        LoginResponse response = userService.loginWithRole(request.getUsername(), request.getPassword());
        if (response == null) {
            return R.fail("用户名或密码错误");
        }

        // 生成包含角色ID的token
        String token = jwtUtil.createToken(
                response.getId(),
                response.getUsername(),
                response.getRoleId()
        );// 设置token
        response.setToken(token);

        return R.ok(response, "登录成功");
    }

    @Operation(summary = "获取用户列表")
    @GetMapping("/list")
    public R<List<User>> list() {
        return R.ok(userService.list(), "项目创建成功");
    }

    @Operation(summary = "根据ID获取用户")
    @GetMapping("/{id}")
    public R<User> getById(@PathVariable Integer id) {
        User user = userService.getById(id);
        return user != null ? R.ok(user, "项目创建成功") : R.fail("用户不存在");
    }
   @Operation(summary = "分页查询用户列表")
    @GetMapping("/page")
    public R<Page<UserDTO>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Integer roleId,
            @RequestParam(required = false) Integer teamId) {

        Page<User> page = new Page<>(current, size);

        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (username != null && !username.trim().isEmpty()) {
            queryWrapper.like(User::getUsername, username);
        }
        if (roleId != null) {
            queryWrapper.eq(User::getRoleId, roleId);
        }
        if (teamId != null) {
            queryWrapper.eq(User::getTeamId, teamId);
        }

        page.setOptimizeCountSql(false);

        // 使用新的服务方法
        Page<UserDTO> result = userService.getUsersWithDetail(page);

        return R.ok(result, "查询成功");
    }
    @Operation(summary = "新增用户")
    @PostMapping("/create")
    public R<Boolean> save(@RequestBody User user) {
        return userService.save(user) ? R.ok(true, "项目创建成功") : R.fail("新增用户失败");
    }

    @Operation(summary = "更新用户")
    @PutMapping
    public R<Boolean> update(@RequestBody User user) {
        return userService.updateById(user) ? R.ok(true, "项目创建成功") : R.fail("更新用户失败");
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")
    public R<Boolean> deleteUser(@PathVariable Integer id) {
        try {
            boolean success = userService.deleteUserAndRelatedData(id);
            return success ?
                    R.ok(true, "删除用户成功") :
                    R.fail("删除用户失败");
        } catch (Exception e) {
            return R.fail("删除失败：" + e.getMessage());
        }
    }
    @Operation(summary = "批量更新用户团队")
    @PutMapping("/batch-update-team")
    public R<Boolean> batchUpdateUserTeam(@RequestBody BatchUpdateTeamRequest request) {
        if (request.getUserIds() == null || request.getUserIds().isEmpty()) {
            return R.fail("用户ID列表不能为空");
        }

        try {
            boolean success = userService.batchUpdateUserTeam(request.getTeamId(), request.getUserIds());
            return success ?
                R.ok(true, "批量更新用户团队成功") :
                R.fail("批量更新用户团队失败");
        } catch (Exception e) {
            return R.fail("批量更新失败：" + e.getMessage());
        }
    }
}